#!/usr/bin/env python3
"""
deepin-devicemanager MCP Server

面向 deepin-devicemanager 软件的 MCP server，提供对 deepin-devicemanager-server.service 的控制功能。

MCP tools 列表：
- deepin_devicemanager_service_control: 控制 deepin-devicemanager-server.service 的启动、停止、重启和重载
  参数: action (str) - 操作类型：start/stop/restart/reload
  返回: JSON 结构包含命令执行结果
"""

from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("Deepin DeviceManager MCP Server")

@mcp.tool()
def deepin_devicemanager_service_control(action: str) -> Dict[str, Any]:
    """
    控制 deepin-devicemanager-server.service 的启动、停止、重启和重载操作
    
    参数:
        action (str): 要执行的操作类型，可选值: start/stop/restart/reload
            - start: 启动服务
            - stop: 停止服务  
            - restart: 重启服务
            - reload: 重载服务配置
    
    返回:
        Dict[str, Any]: 统一的执行结果 JSON 结构
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 实际执行的命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出内容
            "stderr": str         # 标准错误内容
        }
    """
    valid_actions = ["start", "stop", "restart", "reload"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} deepin-devicemanager-server.service",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"无效的操作类型: {action}，支持的操作为: {', '.join(valid_actions)}"
        }
    
    command = ["systemctl", action, "deepin-devicemanager-server.service"]
    
    try:
        result = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=30
        )
        
        return {
            "success": result.returncode == 0,
            "command": " ".join(command),
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
    except subprocess.TimeoutExpired:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": "命令执行超时"
        }
    except Exception as e:
        return {
            "success": False,
            "command": " ".join(command),
            "exit_code": -1,
            "stdout": "",
            "stderr": f"命令执行异常: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()